import { Injectable, OnInit } from "@angular/core";
import { Router, RouterModule } from "@angular/router";
import { Http, Response } from "@angular/http";
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { CookieService } from 'ngx-cookie';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import { GlobalStateService } from "./global-state.service";
import { environment } from '../../environments/environment';

@Injectable() 
export class AuthService implements OnInit {
    private _isLoggedIn:boolean = false;
    private _loggedUserName: string = '';
    private _redirectUrl:string = '';
    private _loginProcess = new Subject();
    constructor( private http: Http,  
        private _router: Router,
        private _cookie: CookieService,
        private _globalState: GlobalStateService) {
    }

    ngOnInit() : void {
        console.log('init auth service');
    }

    setOriginUrl(url: string) {
        this._redirectUrl = url;
    }

    cleanOriginUrl() {
        this.setOriginUrl('');
    }


    //跳转到登录页
    toLogin() {
        if (this._router.url.startsWith('/auth/login')) {
            this.setOriginUrl('/index/dashboard');
        }
        if(this._isLoggedIn) {
            console.log('will go to : ' + this._redirectUrl);
            this._router.navigate([this._redirectUrl]);
        } else {
            this._router.navigate(['/auth/login']);
        }
    }

    checkLogin(): void {
        console.log(this._router.url);
        this._redirectUrl = this._router.url;
        console.log(this._redirectUrl);
        this.toLogin();
    }

    login(username: string, password: string) {
        let loginPromise = this.http.post(environment.endPoint + '/auth/login', 
            JSON.stringify({
                "username": username,
                "password": password
            }));
        this._loginProcess.next(loginPromise.toPromise());
        return loginPromise.map((resp: Response) => {
                let token = resp.json() ? resp.json().token: '';
                console.log(resp.status);
                this._globalState.token = token;
                this._cookie.put('token', token);
                this._cookie.put('roles', resp.json().roles);
                return resp.json;
            });
    }

    loginProcess() {
        return this._loginProcess;
    }

    logout(): void{
        this._isLoggedIn = false;
        // this._cookie.remove('token');
        this.toLogin();
    }
}